package com.sf.dlb.service;

import com.sf.dlb.jpa.model.UserDlbRecordInfo;
import com.sf.dlb.jpa.repository.UserDlbRecordRepository;
import com.sf.dlb.utils.GsonUtils;
import com.sf.dlb.utils.ResultVOUtil;
import com.sf.dlb.utils.StateToValueUtils;
import com.sf.dlb.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by jing.tan on 2018/5/21.
 */
@Service
public class UserDlbRecordService extends BaseUserDlbRecordService{
    private static Logger logger = LoggerFactory.getLogger(UserDlbRecordService.class);

    @Autowired
    private UserDlbRecordRepository userDlbRecordRepository;
    /**
     * 账单详情
     * @param userId
     * @param page
     * @param size
     */
    public ResultVO list(String userId,int page,int size){
        logger.info("list start userId={},page={},size={}",userId,page,size);
        //分页查询
        Sort sort=new Sort(Sort.Direction.DESC,"createDate");
        Pageable pageable= new PageRequest(page,size,sort);
        Page<UserDlbRecordInfo> pageAll=userDlbRecordRepository.findByUserIdAndDelFlag(userId,"0",pageable);
        List<UserDlbRecordInfo> userDlbRecordInfos=pageAll.getContent();
        //封装VO
        List<UserDlbRecordVO> userDlbRecordVOS=new ArrayList<>();
        for (UserDlbRecordInfo userDlbRecordInfo:userDlbRecordInfos) {
            UserDlbRecordVO userDlbRecordVO=new UserDlbRecordVO();
            BeanUtils.copyProperties(userDlbRecordInfo,userDlbRecordVO);
            userDlbRecordVO.setSourceValue(StateToValueUtils.switchUserDlbRecordValue(userDlbRecordInfo.getSource()));
            userDlbRecordVO.setCreateDate(userDlbRecordInfo.getCreateDate().getTime());
            userDlbRecordVOS.add(userDlbRecordVO);
        }
        PageVO pageVO=new PageVO();
        pageVO.setDataList(userDlbRecordVOS);
        pageVO.setPageSize(size);
        pageVO.setCurrentPages(page+1);//默认从0开始，返回前端要+1;
        pageVO.setFirstPage(pageAll.isFirst());
        pageVO.setLastPage(pageAll.isLast());
        pageVO.setTotalElements(pageAll.getTotalElements());
        pageVO.setTotalPages(pageAll.getTotalPages());
        return ResultVOUtil.success(pageVO);
    }
}
